package com.hfmx.aitonguedemo;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.webkit.*;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.hfmx.aitonguedemo.utils.RsaSimpleUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class WebViewActivity extends AppCompatActivity {

    @BindView(R.id.webView)
    WebView webView;
    private ValueCallback<Uri> mUploadMessage;// 表单的数据信息
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int FILECHOOSER_RESULTCODE = 1;// 表单的结果回调</span>
    private static final int REQ_CAMERA = FILECHOOSER_RESULTCODE + 1;//拍照
    private static final int REQ_CHOOSE = REQ_CAMERA + 1; //调用相册
    private Uri imageUri;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = REQ_CHOOSE + 1;
    private static final int ABLUM_PERMISSIONS_REQUEST_CODE = CAMERA_PERMISSIONS_REQUEST_CODE + 1;
    private static final int SCAN_CODE = ABLUM_PERMISSIONS_REQUEST_CODE + 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        String access_token = intent.getStringExtra("access_token");
        try {
            initWebViewSetting(access_token);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //初始化webViewSetting
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void initWebViewSetting(String access_token) throws Exception {
        WebSettings settings = webView.getSettings();
        settings.setBuiltInZoomControls(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setDomStorageEnabled(true);
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setAllowContentAccess(true); // 是否可访问Content Provider的资源，默认值 true
        settings.setAllowFileAccess(true);    // 是否可访问本地文件，默认值 true
        // 是否允许通过file url加载的Javascript读取本地文件，默认值 false
        settings.setAllowFileAccessFromFileURLs(false);
        // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https)，默认值 false
        settings.setAllowUniversalAccessFromFileURLs(false);
        //开启JavaScript支持
        settings.setJavaScriptEnabled(true);
        // 支持缩放
        settings.setSupportZoom(true);
        /**
         * 不同手机相机相册兼容问题
         */
        webView.setWebChromeClient(new MyWebChromeClient());
        /**
         * 微信支付跳转问题
         */
        webView.setWebViewClient(new WebViewClient() {
            String referer = "https://www.ai-tongue.com";

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {
                    if (url.startsWith("weixin://") || url.startsWith("alipays://")) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e) {
                    return false;
                }

                if (url.contains("https://wx.tenpay.com")) {
                    Map extraHeaders = new HashMap<>();
                    extraHeaders.put("Referer", referer);
                    view.loadUrl(url, extraHeaders);
                    return true;
                }
                view.loadUrl(url);
                return true;
            }
        });

       /**
         * 内部点击下载问题
         */
        webView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW,uri);
            startActivity(intent);
        });

        String thirdId = "xxxxxx";
        String rsaPublicKey = "xxxxxx";
        String devRsaPrivateKey = "xxxxxx";
        String encryptedThirdId = RsaSimpleUtil.encrypt(thirdId, rsaPublicKey);
        String signEncryptedThirdId = RsaSimpleUtil.sign(encryptedThirdId, devRsaPrivateKey);
        String url = "https://www.ai-tongue.com/h5/sso?access_token=" + access_token +
                "&encryptedThirdId=" + encryptedThirdId + "&signEncryptedThirdId=" + signEncryptedThirdId;
        //加载地址
        webView.loadUrl(url);
    }

    /**
     * android webview 兼容相机相册选择
     */
    public class MyWebChromeClient extends WebChromeClient {
        // For Android >= 5.0
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mUploadCallbackAboveL = filePathCallback;
            takePhoto();
            return true;
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            takePhoto();
        }

        // For Android  >= 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            takePhoto();
        }

        //For Android  >= 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            takePhoto();
        }
    }

    /**
     * 上传图片
     */
    public void takePhoto() {
        //弹出提示框
        new CommomDialog(this, new CommomDialog.CameraOpenListener() {
            @Override
            public void onClick(CommomDialog c) {
                checkCameraPermission();
                c.dismiss();
            }
        }, new CommomDialog.AblumOpenListener() {
            @Override
            public void onClick(CommomDialog c) {
                showAblum();
                c.dismiss();
            }
        }).show();
    }

    /**
     * 调用相机权限控制
     */
    public void checkCameraPermission() {
        if (ContextCompat.checkSelfPermission(WebViewActivity.this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(WebViewActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(WebViewActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
        } else {
            showCamera();
        }
    }

    /**
     * 调用相机
     */
    public void showCamera() {
        String tempFileName = String.format("image%s.jpg", System.currentTimeMillis());
        File tempFile = new File(Environment.getExternalStorageDirectory(), tempFileName);
        imageUri = Uri.fromFile(tempFile);
        // 在官方7.0的以上的系统中，尝试传递 file://URI可能会触发FileUriExposedException
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(WebViewActivity.this, getPackageName() + ".fileProvider", tempFile);//通过FileProvider创建一个content类型的Uri
        }
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(openCameraIntent, REQ_CAMERA);
    }

    /**
     * 相册权限控制
     */
    public void checkAblumPermission() {
        if (ContextCompat.checkSelfPermission(WebViewActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(WebViewActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, ABLUM_PERMISSIONS_REQUEST_CODE);
        } else {
            showAblum();
        }
    }

    /**
     * 调用相册
     */
    public void showAblum() {
        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
        openAlbumIntent.addCategory(Intent.CATEGORY_OPENABLE);
        openAlbumIntent.setType("image/*");
        startActivityForResult(openAlbumIntent, REQ_CHOOSE);
    }

    /**
     * 权限处理回掉
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSIONS_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //申请成功，可以拍照
                showCamera();
            } else {
                Toast.makeText(WebViewActivity.this, "你拒绝了权限，该功能不可用\n可在应用设置里授权拍照哦", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        if (requestCode == ABLUM_PERMISSIONS_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //申请成功
                showAblum();
            } else {
                Toast.makeText(WebViewActivity.this, "你拒绝了权限，该功能不可用\n可在应用设置里授权查看相册哦", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CHOOSE) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        } else if (requestCode == REQ_CAMERA) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        } else if (requestCode == SCAN_CODE) {
            if (data != null) {
                String arg = data.getStringExtra("result");
                webView.loadUrl("javascript:receptionResult('" + arg + "')");
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
                results = new Uri[]{imageUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        if (results != null) {
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        } else {
            results = new Uri[]{};
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        }
        return;
    }
}
